package com.zbkj.service.dividend.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.PageHelper;
import com.zbkj.common.request.PageParamRequest;
import com.zbkj.common.utils.RedisUtil;
import com.zbkj.service.dividend.dao.DividendPoolConfigMapper;
import com.zbkj.service.dividend.model.DividendPoolConfig;
import com.zbkj.service.dividend.request.DividendPoolConfigRequest;
import com.zbkj.service.dividend.service.DividendPoolConfigService;
import com.zbkj.service.service.SystemConfigService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.Comparator;
import java.util.List;

/**
 * 分红档位配置服务实现类
 */
@Service
public class DividendPoolConfigServiceImpl extends ServiceImpl<DividendPoolConfigMapper, DividendPoolConfig> implements DividendPoolConfigService {

    @Resource
    private DividendPoolConfigMapper dividendPoolConfigMapper;

    @Autowired
    SystemConfigService systemConfigService;

    @Autowired
    private RedisUtil redisUtil;

    private final Long expireTime = 6 * 60 * 60L;

    /**
     * 获取分红档位列表（分页）
     */
    @Override
    public List<DividendPoolConfig> getList(PageParamRequest pageParamRequest) {
        PageHelper.startPage(pageParamRequest.getPage(), pageParamRequest.getLimit());
        return dividendPoolConfigMapper.findPageList(pageParamRequest);
    }

    /**
     * 获取 分红池总额/订单总额 占比配置
     */
    @Override
    public String getTotalPoolRatio(){

        String cacheKey = "dividendTotalRatio";
        String config = redisUtil.get(cacheKey);

        if (ObjectUtils.isEmpty(config)) {
            config = systemConfigService.getValueByKey("total_pool_ratio");
            if (!ObjectUtils.isEmpty(config)) {
                redisUtil.set(cacheKey, config, expireTime);
            }
        }

        return config;
    }

    /**
     * 获取所有启用的分红档位配置
     */
    @Override
    public List<DividendPoolConfig> getAllActiveConfigs() {

        String cacheKey = "dividendConfig";
        List<DividendPoolConfig> configList = redisUtil.get(cacheKey);

        if (CollectionUtils.isEmpty(configList)) {
            configList = dividendPoolConfigMapper.findAllActive();
            if (!CollectionUtils.isEmpty(configList)) {
                // 按档位升序排序
                configList.sort(Comparator.comparing(DividendPoolConfig::getLevel));
                redisUtil.set(cacheKey, configList, expireTime);
            }
        }
        return configList;
    }

    /**
     * 获取用户当前分红配置
     */
    public DividendPoolConfig getCurrentDividendConfig(Integer dividendId) {
        if (dividendId == null || dividendId == 0) {
            return null;
        }

        String cacheKey = "dividend:" + dividendId;
        DividendPoolConfig config = redisUtil.get(cacheKey);

        if (config == null) {
            config = getById(dividendId);
            if (config != null) {
                redisUtil.set(cacheKey, config, expireTime);
            }
        }
        return config;
    }

    /**
     * 新增分红档位配置
     */
    @Override
    public boolean create(DividendPoolConfigRequest request) {
        // 检查档位是否已存在
        int count = dividendPoolConfigMapper.countByLevel(request.getLevel());
        if (count > 0) {
            throw new RuntimeException("分红档位已存在: " + request.getLevel());
        }

        DividendPoolConfig config = new DividendPoolConfig();
        BeanUtils.copyProperties(request, config);
        config.setCreateTime(LocalDateTime.now());
        config.setUpdateTime(LocalDateTime.now());

        return save(config);
    }

    /**
     * 修改分红档位配置
     */
    @Override
    public boolean edit(Integer id, DividendPoolConfigRequest request) {
        // 检查档位是否被其他记录使用
        int count = dividendPoolConfigMapper.countByLevelExcludeId(request.getLevel(), id);
        if (count > 0) {
            throw new RuntimeException("分红档位已被其他记录使用: " + request.getLevel());
        }

        DividendPoolConfig config = getById(id);
        if (config == null) {
            throw new RuntimeException("分红档位配置不存在");
        }

        BeanUtils.copyProperties(request, config);
        config.setUpdateTime(LocalDateTime.now());

        return updateById(config);
    }

    /**
     * 更新状态
     */
    @Override
    public boolean updateStatus(Integer id, Boolean isActive) {
        return dividendPoolConfigMapper.updateStatus(id, isActive) > 0;
    }

    /**
     * 检查档位是否存在
     */
    @Override
    public boolean checkLevelExists(Integer level, Integer excludeId) {
        if (excludeId == null) {
            return dividendPoolConfigMapper.countByLevel(level) > 0;
        } else {
            return dividendPoolConfigMapper.countByLevelExcludeId(level, excludeId) > 0;
        }
    }
}